/********************************************************************************************
** Copyright � 2011 Nokia Corporation. All rights reserved.
** Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation.
** Java and all Java-based marks are trademarks or registered trademarks of
** Sun Microsystems, Inc. Other product and company names mentioned herein may be
** trademarks or trade names of their respective owners.
**
** Subject to the conditions below, you may, without charge:
**
** �  Use, copy, modify and/or merge copies of this software and
**    associated content and documentation files (the �Software�)
**
** �  Publish, distribute, sub-licence and/or sell new software
**    derived from or incorporating the Software.
**
** Some of the documentation, content and/or software maybe licensed under open source
** software or other licenses.  To the extent such documentation, content and/or
** software are included, licenses and/or other terms and conditions shall apply
** in addition and/or instead of this notice. The exact terms of the licenses, disclaimers,
** acknowledgements and notices are reproduced in the materials provided.
**
** This file, unmodified, shall be included with all copies or substantial portions
** of the Software that are distributed in source code form.
**
** The Software cannot constitute the primary value of any new software derived
** from or incorporating the Software.
**
** Any person dealing with the Software shall not misrepresent the source of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
** INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
** PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
** HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
** OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
********************************************************************************************/
import Qt 4.7

import QtMobility.location 1.1

import "DCDataClasses.js" as DCDATA

import GeoHelper 1.0

Rectangle {
    id: mapwindow
    width: 500
    height: 500


    property string datacloudurl: ""
    property string username: ""
    property string password: ""
    property string firstname: ""
    property string lastname: ""
    property string phonenumber: ""
    property string hometown: ""
    property string karpoid: ""
    property string routekarpoid: "0"
    property string routecarpoolkarpoid: "0"

    property bool handleroutes: false

    property bool selectarea: false


    property string todo: ""

    property int jointripactiveind: -1
    property int mytripactiveind: -1

    signal startFollowingCarpool(string carpoolkarpoid)
    signal stopFollowingCarpool()

    function getRoutepolyline() // Note: this is mentioned to be just a temporary helper
    {
        if (newroute.count > 1)
        {
           return JSON.parse(newroute.get(1).routepolyline)
        }


        return []
    }

    function showDriverIcon(lat,lon,putcenter,aliaslabel)
    {

        geohelper.drawImage("drivericon", lat,lon, "./qml/Carpool/driver.png", -16,-37)

        geohelper.drawText("driveralias",  lat,lon, aliaslabel)

        if (putcenter)
        {
            mapid.center.latitude = lat
            mapid.center.longitude = lon
        }
    }

    onVisibleChanged:
    {

    }

    function setJointrip(joining)
    {
        if (!joining)
        {
            selectarea = false

            newRoute()
            jointrip.visible = false
            selectedarea.width = 0
            selectedarea.height = 0
            selectedarea.visible = false

            maptool.drawingarea = false

        }

        joinconfirmation.visible = false
        jointrip.visible = false

        maptool.selectionToolVisilbe(joining)
    }

    function newRoute()
    {
        newroute.setProperty(0, "pointset", false)
        newroute.setProperty(1, "pointset", false)
        geohelper.clearMap()
        addressfromstatus.text = ""
        addresstostatus.text = ""
        distanceandtime.text = ""
        routedetailsid.visible = false
        routeselection.visible = false
        addressid.visible = false
        routeinfo.visible = false
        routekarpoid = "0"
        routecarpoolkarpoid = "0"
        messagebox.visible = false

        jointripactiveind = -1
        mytripactiveind = -1

        routedetailsid.clearData()


    }



    function setHandleroutes(handle)
    {
        handleroutes = handle
        routetool.visible = handle

        newRoute()
    }

    function selectRoute()
    {
        routeselection.x = (mapwindow.width - routeselection.width)/2
        routeselection.visible = true
        routeselection.loadRoutes(true)
    }

    function myTrips()
    {
        mytrips.x = (mapwindow.width - mytrips.width)/2
        mytrips.visible = true
        mytrips.loadTrips()
    }

    function setZoomLevel(zoomDelta)
    {

        var newZoomLevel = mapid.zoomLevel + zoomDelta
        if (newZoomLevel < mapid.maximumZoomLevel &&
                newZoomLevel > mapid.minimumZoomLevel)
        {
            mapid.zoomLevel = newZoomLevel
        }
    }


    function showRouteInfo(ind)
    {
        routeinfo.x = (mapwindow.width - routeinfo.width)/2
        var traveltime = newroute.get((ind+1)).traveltime
        var distance = newroute.get((ind+1)).distance
        if (traveltime == undefined)
        {
            traveltime = ""
        }
        else
        {
            traveltime = DCDATA.secondToHMS(newroute.get((ind+1)).traveltime)
        }
        if (distance == undefined)
        {
            distance = 0
        }
        else
        {
            distance = distance / 1000
        }

        // Route's starting point holds the additional information
        /*
        ownerkarpoid: ""
        ownername: ""
        ownerhometown: ""
        ownerphone: ""
        time: ""
        repeat: ""
        */
        var repeat = ""
        var time = ""
        var ownername = ""
        var ownerhometown = ""
        var ownerphone = ""
        if (routetool.visible)
        {
            // either new route or a saved one is opened => in any case this is user's own and
            // the details if any are stored in the routedetailsid dialog
            repeat = routedetailsid.routerepeat
            time = routedetailsid.routetime
            ownername =  routedetailsid.showownername=="1"?mapwindow.firstname + " " + mapwindow.lastname:"NA"
            ownerhometown = routedetailsid.showownerhometown=="1"?mapwindow.hometown:"NA"
            ownerphone = routedetailsid.showownerphone=="1"?mapwindow.phonenumber:"NA"
        }
        else
        {
            if (mytripactiveind > -1)
            {

                ind1 = mytripactiveind

                console.log("=====> MYTRIP IND1 = "+ind1)



                repeat = mytrips.getRouteRepeatInd(ind1)
                time = mytrips.getRouteTimeInd(ind1)

                ownername =  mytrips.getRouteOwnerName(ind1)
                ownerhometown = mytrips.getRouteOwnerHometown(ind1)
                ownerphone = mytrips.getRouteOwnerPhone(ind1)


            }
            else
            {
                // in this case the route is opend with map area and the user is selecting a trip to join
                // the details can be asked from jointrip dialog
                var ind1 = Math.round((ind - 0.5))
                if (jointripactiveind > -1)
                {
                    ind1 = jointripactiveind
                }

                console.log("=====> IND1 = "+ind1)

                repeat = jointrip.getRouteRepeatInd(ind1)
                time = jointrip.getRouteTimeInd(ind1)

                ownername =  jointrip.getRouteOwnerName(ind1)
                ownerhometown = jointrip.getRouteOwnerHometown(ind1)
                ownerphone = jointrip.getRouteOwnerPhone(ind1)

            }
        }

        routeinfo.setInfo(
                    newroute.get(ind).latitude,newroute.get(ind).longitude,
                    newroute.get(ind).street,newroute.get(ind).city,newroute.get(ind).country,
                    newroute.get((ind+1)).latitude,newroute.get((ind+1)).longitude,
                    newroute.get((ind+1)).street,newroute.get((ind+1)).city,newroute.get((ind+1)).country,
                    distance,traveltime,repeat,time,ownername,ownerhometown,ownerphone)
    }


    function areaReady(fromorto)
    {
        // get the routes/carpools in this area...
        var arr = map.getSelectedAreaCoordinates()

        jointrip.x = (map.width - jointrip.width)/2
        jointrip.getRoutes(fromorto,arr[0],arr[1],arr[2],arr[3]);
    }


    ListModel
    {
        id: newroute
        ListElement
        {
            type: "FROMPOINT"
            pointset: false
            latitude: 0.0
            longitude: 0.0
            country: ""
            countryCode: ""
            state: ""
            city: ""
            district: ""
            street: ""
            postcode: ""
            distance: 0
            traveltime: 0
            routepolyline: ""
        }
        ListElement
        {
            type: "TOPOINT"
            pointset: false
            latitude: 0.0
            longitude: 0.0
            country: ""
            countryCode: ""
            state: ""
            city: ""
            district: ""
            street: ""
            postcode: ""
            distance: 0
            traveltime: 0
            routepolyline: ""

        }
    }



    Crosshair
    {
        id: crosshair
        visible: false
        anchors.centerIn: parent

        onCrosshairSelect:
        {
            // x,y
            messagebox.showInfo("Calculating the point ...")
            mapid.center = mapid.toCoordinate(Qt.point(x, y))
            geohelper.findAddress(mapid.center.latitude, mapid.center.longitude)
        }
    }


    RouteTool
    {
        id: routetool
        visible: false

        onFromWithMapSelected:
        {
            crosshair.visible = true
            todo = "setFromPoint"
        }

        onFromWithAddressSelected:
        {
            crosshair.visible = false
            todo = "setFromAddress"

            addressid.x = (mapwindow.width - addressid.width)/2
            addressid.street = ""
            addressid.city = ""
            addressid.country = ""
            if (newroute.get(0).pointset)
            {
                if (newroute.get(0).street != undefined)
                {
                    addressid.street = newroute.get(0).street
                }
                if (newroute.get(0).city != undefined)
                {
                    addressid.city = newroute.get(0).city
                }
                if (newroute.get(0).country != undefined)
                {
                    addressid.country = newroute.get(0).country
                }


            }

            addressid.visible = true
        }

        onToWithMapSelected:
        {
            crosshair.visible = true
            todo = "setToPoint"

        }

        onToWithAddressSelected:
        {
            crosshair.visible = false
            todo = "setToAddress"

            addressid.x = (mapwindow.width - addressid.width)/2
            addressid.street = ""
            addressid.city = ""
            addressid.country = ""
            if (newroute.get(1).pointset)
            {
                if (newroute.get(1).street != undefined)
                {
                    addressid.street = newroute.get(1).street
                }
                if (newroute.get(1).city != undefined)
                {
                    addressid.city = newroute.get(1).city
                }
                if (newroute.get(1).country != undefined)
                {
                    addressid.country = newroute.get(1).country
                }


            }

            addressid.visible = true
        }

        onClearFromOrToTool:
        {
            crosshair.visible = false
            todo = ""
        }

        onRouteInfoSelected:
        {
            if (!newroute.get(0).pointset)
            {
                messagebox.text = "Set the start point first."
                messagebox.show("")
            }
            else if (!newroute.get(1).pointset)
            {
                messagebox.text = "Set the end point first."
                messagebox.show("")
            }
            else
            {
                showRouteInfo(0)
            }
        }

        onRouteOkSelected:
        {

            if (!newroute.get(0).pointset)
            {
                messagebox.text = "Set the start point first."
                messagebox.show("")
            }
            else if (!newroute.get(1).pointset)
            {
                messagebox.text = "Set the end point first."
                messagebox.show("")
            }
            else
            {
                // ask the route's details and save it
                routedetailsid.x = (mapwindow.width - routedetailsid.width)/2
                todo = ""
                crosshair.visible = false
                routedetailsid.init()
            }

        }

        onVisibleChanged:
        {
            if (!visible)
            {
                todo = ""
                if (crosshair.visible)
                {
                    crosshair.visible = false
                }
            }

        }


    }


    function saveroutecb(response)
    {
        console.log("saveroutedb response: " + response)
        var count = 0
        var result = {}
        try
        {
            result = JSON.parse(response)
            count = result["result"]["rows updated or added"]
        }
        catch (e)
        {
        }

        if (count < 1)
        {
            messagebox.text = "Failed to save the route."
        }
        else
        {
            messagebox.text = "Route saved."

            // update also the routekarpoid and routename in the KarpoCarpoolsIndex
            newRoute()
        }
    }

    RouteDetails
    {
        id: routedetailsid
        visible: false

        onDetailsSave:
        {
            if (routedetailsid.routename == "")
            {
                messagebox.text = "The name of the route is mandatory."
                messagebox.show("")
            }
            else
            {

                routedetailsid.visible = false

                messagebox.text = "Saving the route..."
                messagebox.show("")

                //dculr, karpoid, ownerkarpoid, name, description, time, repeate, route, saveroutecb

                // do not save the route polyline; it is dynamcially restored when this route is loaded
                newroute.setProperty(1, "routepolyline", "[]")

                var dcroute = new DCDATA.DCRoute()
                dcroute.karpoid = karpoid
                dcroute.password = password
                dcroute.routekarpoid = routekarpoid
                dcroute.ownerkarpoid = karpoid
                dcroute.name = routename
                dcroute.description = routedescriptions
                dcroute.time = routetime
                dcroute.repeat = routerepeat

                dcroute.route[0] = newroute.get(0)
                dcroute.route[1] = newroute.get(1)

                dcroute.lat1 = newroute.get(0).latitude
                dcroute.lon1 = newroute.get(0).longitude
                dcroute.lat2 = newroute.get(1).latitude
                dcroute.lon2 = newroute.get(1).longitude

                dcroute.showownername = showownername
                dcroute.showownerhometown = showownerhometown
                dcroute.showownerphone = showownerphone

                dcroute.carpoolkarpoid = freecarpoolkarpoarr[carpoolarrind].carpoolkarpoid

                DCDATA.send(dcroute, datacloudurl, "saveroute", saveroutecb)

            }
        }

        function saveroutecb(response)
        {
            console.log("RouteDetails::saveroutecb: " + response.statusString)

            if (response.isError)
            {
                messagebox.text = "Failed: " + response.errorString
            }
            else
            {
                messagebox.visible = false
            }
        }



        onDetailsCancel:
        {
            routedetailsid.visible = false
        }
    }

    AddressSetting
    {
        id: addressid
        visible: false

        onAddressOk:
        {
            messagebox.showInfo("Calculating the point ...")
            addressid.visible = false
            geohelper.findCoordinates(addressid.street,addressid.city,addressid.country)
        }

        onAddressCancel:
        {
            todo = ""
            addressid.visible = false
        }
    }

/*
[
    {
        "coordinate":
            {
                "latitude":61.4157,
                "longitude":24.079
            },
        "address":
            {
                "country":"FINLAND",
                "countryCode":"FIN",
                "state":"",
                "county":"",
                "city":"Kangasala",
                "district":"",
                "street":"37 Piirinrannantie",
                "postcode":"36270"
            }
    }
]

reply[i].coordinate.latitude


*/



    GeoHelper
    {
        id: geohelper
        map: mapid

        onDebugMsg:
        {
            //console.log("onDebugMsg: " + reply)
        }

        onRoutingError:
        {
            messagebox.text = "Routing error: " + error
            messagebox.show("")
            //console.log("MSG: " + error)
        }

        onRoutingReply:
        {

            var replyArray = JSON.parse(reply)
            if (replyArray.length > 0)
            {

                for (var i = 0; i < replyArray.length; i++)
                {
                    var lat1 = replyArray[i].lat1
                    var lon1 = replyArray[i].lon1
                    var lat2 = replyArray[i].lat2
                    var lon2 = replyArray[i].lon2

                    if (joinconfirmation.routestartlat == lat1 && joinconfirmation.routestartlon == lon1 &&
                            joinconfirmation.picklat == lat2 && joinconfirmation.picklon == lon2)
                    {
                        joinconfirmation.routestartlat = 0
                        joinconfirmation.routestartlon = 0
                        joinconfirmation.picklat = 0
                        joinconfirmation.picklon = 0
                        joinconfirmation.setDistanceAndTraveltime(replyArray[i].distance,replyArray[i].travelTime)

                    }
                    else
                    {
                        var routeid = "route"
                        var startpointind = 0

                        // find the start/endpoint
                        for (var n = 0; n < newroute.count; n=n+2) // every other ie the startpoint 0,2,4,...
                        {
                            if (newroute.get(n).latitude == lat1 && newroute.get(n).longitude == lon1)
                            {
                                if (newroute.count > n)
                                {
                                    if (newroute.get((n+1)).latitude == lat2 && newroute.get((n+1)).longitude == lon2)
                                    {
                                        routeid = "route-" + n
                                        startpointind = n
                                    }
                                }
                            }
                        }

                        if (newroute.get(startpointind).pointset && newroute.get((startpointind+1)).pointset)
                        {
                            newroute.setProperty((startpointind+1), "distance", replyArray[i].distance)
                            newroute.setProperty((startpointind+1), "traveltime", replyArray[i].travelTime)
                            newroute.setProperty((startpointind+1), "routepolyline", JSON.stringify(replyArray[i].path))


                            geohelper.drawPolyline(routeid,newroute.get((startpointind+1)).routepolyline)


                            distanceandtime.text = ""
                            if (newroute.count < 2)
                            {
                                distanceandtime.text = "" + replyArray[i].distance/1000 + " km, " + DCDATA.secondToHMS(replyArray[i].travelTime)
                            }
                        }
                    }
                }

            }
            messagebox.visible = false
        }

        onSearchError:
        {
            messagebox.text = error
            messagebox.show("")
        }

        onSearchReply:
        {

            messagebox.visible = false
            var replyArray = JSON.parse(reply)
            if (replyArray.length > 0)
            {

                for (var i = 0; i < replyArray.length; i++)
                {
                    var index = -1
                    if (todo == "setFromAddress" || todo == "setFromPoint")
                    {
                        index = 0
                    }
                    else if (todo == "setToAddress" || todo == "setToPoint")
                    {
                        index = 1
                    }


                    if (index > -1)
                    {
                        newroute.setProperty(index, "latitude", replyArray[i].coordinate.latitude)
                        newroute.setProperty(index, "longitude", replyArray[i].coordinate.longitude)
                        newroute.setProperty(index, "country", replyArray[i].address.country)
                        newroute.setProperty(index, "countryCode", replyArray[i].address.countryCode)
                        newroute.setProperty(index, "state", replyArray[i].address.state)
                        newroute.setProperty(index, "county", replyArray[i].address.county)
                        newroute.setProperty(index, "city", replyArray[i].address.city)
                        newroute.setProperty(index, "district", replyArray[i].address.district)
                        newroute.setProperty(index, "street", replyArray[i].address.street)
                        newroute.setProperty(index, "postcode", replyArray[i].address.postcode)
                        newroute.setProperty(index, "pointset", true)

                        if (index == 0)
                        {
                            addressfromstatus.text = replyArray[i].address.street + ", " + replyArray[i].address.postcode + " " + replyArray[i].address.city
                            geohelper.drawImage("startpoint", newroute.get(0).latitude, newroute.get(0).longitude, "./qml/Carpool/routestart.png", -10,-34)
                            mapid.center.latitude = newroute.get(0).latitude
                            mapid.center.longitude = newroute.get(0).longitude

                        }
                        else
                        {
                            geohelper.drawImage("endpoint", newroute.get(1).latitude, newroute.get(1).longitude, "./qml/Carpool/routeend.png", -10,-34)
                            addresstostatus.text = replyArray[i].address.street + ", " + replyArray[i].address.postcode + " " + replyArray[i].address.city
                        }
                    }

                    if (newroute.get(0).pointset && newroute.get(1).pointset)
                    {
                        messagebox.showInfo("Calculating the route ...")
                        geohelper.findRoute(newroute.get(0).latitude, newroute.get(0).longitude, newroute.get(1).latitude, newroute.get(1).longitude);
                    }
                }

            }
        }


        onGeomapobjectSelected:
        {
            console.log("GEOMAPOBJECT SELECTED: " + id)

            var pos = id.indexOf("-")
            var str = id
            var ind = 0
            if (pos > -1)
            {
                str = id.substr(0,pos);
                ind = parseInt(id.substr(pos+1))
                if (str == "endpoint")
                {
                    ind--
                }
            }
            console.log("GEOMAPOBJECT SELECTED str: " + str + ", ind: " + ind)

            if (str == "startpoint" || str == "endpoint" || str == "route")
            {
               showRouteInfo(ind)
            }

        }
    }

    RouteInfo
    {
        id: routeinfo
        visible: false
    }


    Map {
        id: mapid

        //connectivityMode: Map.OfflineMode
        plugin : Plugin {
                            name : "nokia"
                        }
        size.width: parent.width
        size.height: parent.height
        zoomLevel: 7
        center: Coordinate {
                    latitude: 61.4471
                    longitude: 23.8639
                }



    }



    function getSelectedAreaCoordinates()
    {
        var bottomleftx = selectedarea.x
        var bottomlefty = selectedarea.y+selectedarea.height
        var toprightx = selectedarea.x+selectedarea.width
        var toprighty = selectedarea.y

        var coordinateleft = mapid.toCoordinate(Qt.point(bottomleftx, bottomlefty))
        var coordinateright = mapid.toCoordinate(Qt.point(toprightx, toprighty))

        var arr = []
        arr[0] = coordinateleft.latitude
        arr[1] = coordinateleft.longitude
        arr[2] = coordinateright.latitude
        arr[3] = coordinateright.longitude

        return arr
    }

    Rectangle
    {
        id: selectedarea
        color: "lightgreen"
        border.color: "black"
        opacity: 0.4
        visible: false
        width: 1
        height: 1

        property int startx: 0
        property int starty: 0
    }


    MouseArea {

        anchors.fill : parent

        property bool mouseDown : false
        property int lastX : -1
        property int lastY : -1

        property bool mouseMoved: false

        hoverEnabled : true

        onPressed : {
            mouseDown = true
            lastX = mouse.x
            lastY = mouse.y
            mouseMoved = false
            if (selectarea)
            {
                selectedarea.x = lastX
                selectedarea.y = lastY
                selectedarea.startx = lastX
                selectedarea.starty = lastY
                selectedarea.visible = true
                selectedarea.width = 1
                selectedarea.height = 1

            }
        }
        onReleased : {
            mouseDown = false
            lastX = -1
            lastY = -1
        }
        onPositionChanged: {
            if (mouseDown) {
                var dx = mouse.x - lastX
                var dy = mouse.y - lastY
                lastX = mouse.x
                lastY = mouse.y
                mouseMoved = true
                if (selectarea)
                {
                    if (lastX < selectedarea.startx)
                    {
                        var w = selectedarea.startx - lastX
                        selectedarea.x = lastX
                        selectedarea.width = w
                    }
                    else
                    {
                        selectedarea.width = lastX - selectedarea.startx
                    }

                    if (lastY < selectedarea.starty)
                    {
                        var h = selectedarea.starty - lastY
                        selectedarea.y = lastY
                        selectedarea.height = h
                    }
                    else
                    {
                        selectedarea.height = lastY - selectedarea.starty
                    }


                }
                else
                {

                    mapid.pan(-dx, -dy)
                }
            }
        }

        onClicked:
        {
            // Do not show info about a mapobject if the map is just moved.
            if (!mouseMoved)
            {
                var coordinate = mapid.toCoordinate(Qt.point(mouse.x, mouse.y))
                geohelper.findObjectsInCoordinates(coordinate.latitude,coordinate.longitude)
            }
        }

        onDoubleClicked: {

        }
    }

    Text {
        id: addressfromstatus
        color: "black"
        text: ""
        style: Text.Outline
        styleColor: "#AAAAAA"
        font.family: "Arial"
        anchors.bottom: addresstostatus.top
        anchors.bottomMargin: 3
        anchors.left: parent.left
        anchors.leftMargin: 5
        font.pixelSize: 14
        visible:  routetool.visible

    }

    Text {
        id: addresstostatus
        color: "black"
        text: ""
        style: Text.Outline
        styleColor: "#AAAAAA"
        font.family: "Arial"
        anchors.bottom: distanceandtime.top
        anchors.bottomMargin: 3
        anchors.left: parent.left
        anchors.leftMargin: 5
        font.pixelSize: 14
        visible:  routetool.visible
    }

    Text {
        id: distanceandtime
        color: "black"
        text: ""
        style: Text.Outline
        styleColor: "#AAAAAA"
        font.family: "Arial"
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 3
        anchors.left: parent.left
        anchors.leftMargin: 5
        font.pixelSize: 14
        visible:  routetool.visible
    }

    MessageBox
    {
        id: messagebox

        function showInfo(msg)
        {
            messagebox.text = msg
            messagebox.show("")
        }
    }


    MapTool
    {
        id: maptool
        anchors.right: parent.right
        anchors.rightMargin: 0
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 0
        visible: map.visible

        onZoomIn:
        {
            map.setZoomLevel(1)
        }

        onZoomOut:
        {
            map.setZoomLevel(-1)
        }

        onSelectarea:
        {
            mapwindow.selectarea = selecting
            selectedarea.visible = selecting
        }

        onAreaselected:
        {
            mapwindow.selectarea = false
            mapwindow.areaReady(fromorto);
        }

        onResetArea:
        {
            selectedarea.width = 0
            selectedarea.height = 0
        }

    }


    JoinTrip
    {
        id: jointrip
        datacloudurl: mapwindow.datacloudurl
        username: mapwindow.username
        password: mapwindow.password
        karpoid: mapwindow.karpoid


        visible: false

        onShowroute:
        {
            newRoute()

            newroute.clear();
            jointripactiveind = jointrip.getActiveInd()
            newroute.append(jointrip.getRouteFrom())
            newroute.append(jointrip.getRouteTo())

            addressfromstatus.text = newroute.get(0).street + ", " + newroute.get(0).postcode + " " + newroute.get(0).city
            geohelper.drawImage("startpoint-0", newroute.get(0).latitude, newroute.get(0).longitude, "./qml/Carpool/routestart.png", -10,-34)
//            mapid.center.latitude = newroute.get(0).latitude
//            mapid.center.longitude = newroute.get(0).longitude

            geohelper.drawImage("endpoint-1", newroute.get(1).latitude, newroute.get(1).longitude, "./qml/Carpool/routeend.png", -10,-34)
            addresstostatus.text = newroute.get(1).street + ", " + newroute.get(1).postcode + " " + newroute.get(1).city

            if (newroute.get(0).pointset && newroute.get(1).pointset)
            {
                messagebox.showInfo("Calculating the route ...")
                geohelper.findRoute(newroute.get(0).latitude, newroute.get(0).longitude, newroute.get(1).latitude, newroute.get(1).longitude);
            }
        }

        onShowAllroute:
        {
            newRoute()
            newroute.clear();

            jointripactiveind = -1

            for (var r = 0; r < jointrip.getRouteCount(); r++)
            {

                newroute.append(jointrip.getRouteFromInd(r))
                newroute.append(jointrip.getRouteToInd(r))

                var i = newroute.count - 2

                var startpoint = "startpoint-" + i
                var endpoint = "endpoint-" + (i+1)
                geohelper.drawImage(startpoint, newroute.get(i).latitude, newroute.get(i).longitude, "./qml/Carpool/routestart.png", -10,-34)

                geohelper.drawImage(endpoint, newroute.get((i+1)).latitude, newroute.get((i+1)).longitude, "./qml/Carpool/routeend.png", -10,-34)

                if (newroute.get(i).pointset && newroute.get((i+1)).pointset)
                {
                    messagebox.showInfo("Calculating the route ...")
                    geohelper.findRoute(newroute.get(i).latitude, newroute.get(i).longitude, newroute.get((i+1)).latitude, newroute.get((i+1)).longitude);
                }
            }

        }

        onCancel:
        {
            newRoute()
            jointrip.visible = false
            selectedarea.width = 0
            selectedarea.height = 0
            selectedarea.visible = false
        }

        onRouteselected:
        {
            selectedarea.width = 0
            selectedarea.height = 0
            selectedarea.visible = false

            jointrip.showroute()
            joinconfirmation.initConfirmation()

            joinconfirmation.visible = true
            jointrip.visible = false

        }


    }

    JoinConfirmation
    {
        id: joinconfirmation
        karpoid: mapwindow.karpoid
        datacloudurl: mapwindow.datacloudurl

        x: (map.width - joinconfirmation.width)/2


        property double routestartlat: 0
        property double routestartlon: 0
        property double picklat: 0
        property double picklon: 0

        function initConfirmation()
        {
            var ind = jointrip.getActiveInd()

            var routename = jointrip.getRouteNameInd(ind)
            var routedesc = jointrip.getRouteDescriptionInd(ind)

            var routetime = jointrip.getRouteTimeInd(ind)
            var routerepeat = jointrip.getRouteRepeatInd(ind)

            var ownername = jointrip.getRouteOwnerName(ind)
            var ownerhometown = jointrip.getRouteOwnerHometown(ind)
            var ownerphone = jointrip.getRouteOwnerPhone(ind)
            var ownerphonepassprivacy = jointrip.getRouteOwnerPhonePassPrivacy(ind)

            var routefrom = jointrip.getRouteFromInd(ind)
            var routeto = jointrip.getRouteToInd(ind)

            var routekarpoid = jointrip.getRouteKarpoidInd(ind)
            var ownerkarpoid = jointrip.getRouteOwnerKarpoidInd(ind)

            var carpoolkarpoid = jointrip.getRouteCarpoolkarpoidInd(ind)

            setInfo(routename,routedesc,routetime,routerepeat,ownername,ownerhometown,ownerphone,routefrom,routeto,routekarpoid,carpoolkarpoid,ownerkarpoid,ownerphonepassprivacy)
        }

        onPicklocation:
        {
            joinconfirmation.visible = false
            picklocation.visible = true
        }

        onFindRoute:
        {

            routestartlat = fromlatitude
            routestartlon = fromlongitude
            picklat = picklatitude
            picklon = picklongitude
            geohelper.findRoute(fromlatitude, fromlongitude, picklatitude,picklongitude)
        }

        onDrawImageOnMap:
        {
            console.log("onDrawImageOnMap: " + id + "," + latitude + "," +  longitude + "," +  img + "," +  xOffset + "," +  yOffset)
            geohelper.drawImage(id, latitude, longitude, img, xOffset, yOffset)
        }

        onClearMap:
        {
            mapwindow.newRoute()
        }
    }

    MyTrips
    {
        id: mytrips
        visible: false

        datacloudurl: mapwindow.datacloudurl
        username: mapwindow.username
        password: mapwindow.password
        karpoid: mapwindow.karpoid

        onShowroute:
        {
            newRoute()

            newroute.clear();
            mytripactiveind = mytrips.getActiveInd()
            newroute.append(mytrips.getRouteFrom())
            newroute.append(mytrips.getRouteTo())

            addressfromstatus.text = ""
            geohelper.drawImage("startpoint-0", newroute.get(0).latitude, newroute.get(0).longitude, "./qml/Carpool/routestart.png", -10,-34)
            mapid.center.latitude = newroute.get(0).latitude
            mapid.center.longitude = newroute.get(0).longitude

            geohelper.drawImage("endpoint-1", newroute.get(1).latitude, newroute.get(1).longitude, "./qml/Carpool/routeend.png", -10,-34)
            addresstostatus.text = newroute.get(1).street + ", " + newroute.get(1).postcode + " " + newroute.get(1).city

            if (newroute.get(0).pointset && newroute.get(1).pointset)
            {
                messagebox.showInfo("Calculating the route ...")
                geohelper.findRoute(newroute.get(0).latitude, newroute.get(0).longitude, newroute.get(1).latitude, newroute.get(1).longitude);
            }
        }

        onDrawImageOnMap:
        {
            console.log("onDrawImageOnMap: " + id + "," + latitude + "," +  longitude + "," +  img + "," +  xOffset + "," +  yOffset)
            geohelper.drawImage(id, latitude, longitude, img, xOffset, yOffset)
        }

        onClearMap:
        {
            mapwindow.newRoute()
        }

        onStartFollowing:
        {
            // carpoolkarpoid
            console.log("Map::MyTrips:onStartFollowing carpoolid = " + carpoolkarpoid)

            mapwindow.startFollowingCarpool( carpoolkarpoid)

        }

        onStopFollowing:
        {
            console.log("Map::MyTrips:onStopFollowing")
            mapwindow.stopFollowingCarpool()
        }
    }

    RouteSelection
    {
        id: routeselection
        visible: false
        datacloudurl: mapwindow.datacloudurl
        username: mapwindow.username
        password: mapwindow.password
        karpoid: mapwindow.karpoid

        onOpened:
        {
            newRoute()

            mapwindow.routekarpoid = routeselection.getRouteKarpoId()

            console.log("MAP::RouteSelection::onOpend => routekarpoid=> " + mapwindow.routekarpoid)

            routedetailsid.routename = routeselection.getRouteName()
            routedetailsid.routedescriptions = routeselection.getRouteDescription()
            routedetailsid.routetime = routeselection.getRouteTime()
            routedetailsid.setRepeat(routeselection.getRouteRepeat())
            routedetailsid.showownername = routeselection.getRouteShowownername()
            routedetailsid.showownerhometown = routeselection.getRouteShowownerhometown()
            routedetailsid.showownerphone = routeselection.getRouteShowownerphone()
            routedetailsid.routekarpoid = routeselection.getRouteKarpoId()
            routedetailsid.routecarpoolkarpoid = routeselection.getRouteCarpoolkarpoid()


            newroute.clear();
            newroute.append(routeselection.getRouteFrom())
            newroute.append(routeselection.getRouteTo())

            routeselection.visible = false


            addressfromstatus.text = newroute.get(0).street + ", " + newroute.get(0).postcode + " " + newroute.get(0).city
            geohelper.drawImage("startpoint", newroute.get(0).latitude, newroute.get(0).longitude, "./qml/Carpool/routestart.png", -10,-34)
            mapid.center.latitude = newroute.get(0).latitude
            mapid.center.longitude = newroute.get(0).longitude

            geohelper.drawImage("endpoint", newroute.get(1).latitude, newroute.get(1).longitude, "./qml/Carpool/routeend.png", -10,-34)
            addresstostatus.text = newroute.get(1).street + ", " + newroute.get(1).postcode + " " + newroute.get(1).city

            if (newroute.get(0).pointset && newroute.get(1).pointset)
            {
                messagebox.showInfo("Calculating the route ...")
                geohelper.findRoute(newroute.get(0).latitude, newroute.get(0).longitude, newroute.get(1).latitude, newroute.get(1).longitude);
            }


            /*
            ListElement
            {
                type: "FROMPOINT"
                pointset: false
                latitude: 0.0
                longitude: 0.0
                country: ""
                countryCode: ""
                state: ""
                city: ""
                district: ""
                street: ""
                postcode: ""
                distance: 0
                traveltime: 0
                routepolyline: ""
            }

            console.log("=> " + routeselection.getRouteFrom())
            console.log("=> " + routeselection.getRouteTo())
            */
        }

    }


    PickLocation
    {
        id: picklocation
        anchors.centerIn: parent
        visible: false


        onLocationpicked:
        {
            var coord = mapid.toCoordinate(Qt.point(x, y))
            joinconfirmation.locationPicked(coord.latitude,coord.longitude)
            picklocation.visible = false
            joinconfirmation.visible = true

        }

    }
}
